<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-06-18 16:13:48
 * @Description: 测站信息管理模块
-->
<template>
  <div class="station-info-management" :style="{ height: view.height - 120 + 'px' }">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="测站编码">
          <el-input
            v-model="searchForm.stcd"
            placeholder="请输入测站编码"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="测站名称">
          <el-input
            v-model="searchForm.stnm"
            placeholder="请输入测站名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="数据来源">
          <el-input
            v-model="searchForm.source"
            placeholder="请输入数据来源"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="测站类型">
          <el-select
            v-model="searchForm.stationTypeCode"
            placeholder="请选择测站类型"
            style="width: 200px"
            clearable
            filterable
            @change="handleStationTypeCodeChange"
          >
            <el-option
              v-for="type in stationTypes"
              :key="type.stationTypeCode"
              :label="type.stationTypeName"
              :value="type.stationTypeCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card" shadow="never">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增测站
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="success" @click="handleBatchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%" 
        :height="view.height - 480"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="stcd" label="测站编码" width="120" />
        <el-table-column prop="stnm" label="测站名称"  />
        <el-table-column prop="lon" label="经度" width="100">
          <template #default="scope">
            {{ scope.row.lon ? scope.row.lon.toFixed(6) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="lat" label="纬度" width="100">
          <template #default="scope">
            {{ scope.row.lat ? scope.row.lat.toFixed(6) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="source" label="数据来源"  />
        <el-table-column prop="geo" label="地理位置" width="150" />
        <el-table-column prop="stationTypeCode" label="测站类型" width="120">
          <template #default="scope">
            {{ getStationTypeName(scope.row.stationTypeCode) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="测站编码" prop="stcd">
          <el-input
            v-model="formData.stcd"
            placeholder="请输入测站编码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="测站名称" prop="stnm">
          <el-input v-model="formData.stnm" placeholder="请输入测站名称" />
        </el-form-item>
        <el-form-item label="经度" prop="lon">
          <el-input-number
            v-model="formData.lon"
            :precision="6"
            :min="-180"
            :max="180"
            placeholder="请输入经度"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input-number
            v-model="formData.lat"
            :precision="6"
            :min="-90"
            :max="90"
            placeholder="请输入纬度"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="数据来源">
          <el-input v-model="formData.source" placeholder="请输入数据来源" />
        </el-form-item>
        <el-form-item label="地理位置">
          <el-input v-model="formData.geo" placeholder="请输入地理位置信息" />
        </el-form-item>
        <el-form-item label="测站类型" prop="stationTypeCode">
          <el-select
            v-model="formData.stationTypeCode"
            placeholder="请选择测站类型"
            style="width: 100%"
            filterable
            @change="handleFormStationTypeChange"
          >
            <el-option
              v-for="type in stationTypes"
              :key="type.stationTypeCode"
              :label="type.stationTypeName"
              :value="type.stationTypeCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="测站详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="测站编码">
          {{ detailData.stcd }}
        </el-descriptions-item>
        <el-descriptions-item label="测站名称">
          {{ detailData.stnm || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="经度">
          {{ detailData.lon ? detailData.lon.toFixed(6) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="纬度">
          {{ detailData.lat ? detailData.lat.toFixed(6) : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="数据来源">
          {{ detailData.source || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="地理位置">
          {{ detailData.geo || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="测站类型">
          {{ getStationTypeName(detailData.stationTypeCode) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(detailData.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(detailData.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="importVisible" title="批量导入测站信息" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls,.csv"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 .xlsx、.xls、.csv 格式文件，大小不超过10MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleImportConfirm"
            :loading="importLoading"
            :disabled="fileList.length === 0"
          >
            确定导入
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus, Delete, Upload, Download, UploadFilled } from "@element-plus/icons-vue";
import api from "@/api/api"; // 假设这是您的 API 文件路径
import axios from "axios";

// 响应式数据
const loading = ref(false);
const saveLoading = ref(false);
const importLoading = ref(false);
const dialogVisible = ref(false);
const detailVisible = ref(false);
const importVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref('');

// 表格数据
const tableData = ref([]);
const selectedRows = ref([]);
const stationTypes = ref([]);

// 搜索表单
const searchForm = reactive({
  stcd: '',
  stnm: '',
  source: '',
  stationTypeCode: ''
});

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 表单数据和规则
const formRef = ref();
const formData = reactive({
  id: '',
  stcd: '',
  stnm: '',
  lon: null,
  lat: null,
  source: '',
  geo: '',
  stationTypeCode: ''
});

const formRules = reactive({
  stcd: [
    { required: true, message: '请输入测站编码', trigger: 'blur' },
    { min: 1, max: 50, message: '编码长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  stnm: [
    { min: 1, max: 100, message: '名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  lon: [
    { type: 'number', min: -180, max: 180, message: '经度范围为 -180 到 180', trigger: 'blur' }
  ],
  lat: [
    { type: 'number', min: -90, max: 90, message: '纬度范围为 -90 到 90', trigger: 'blur' }
  ],
  stationTypeCode: [
    { required: true, message: '请选择测站类型', trigger: 'change' }
  ]
});

// 详情数据
const detailData:any = reactive({});

// 文件上传
const uploadRef = ref();
const fileList = ref([]);


// 生命周期
onMounted(() => {
  loadData();
  loadStationTypes();
});

// 窗口大小变化监听
window.onresize = () => {
  view.height = window.innerHeight;
};

// 方法定义
const loadData = async () => {
  loading.value = true;
  try {
    // 清理空参数，避免发送空字符串参数
    const cleanParams = {};
    Object.keys(searchForm).forEach(key => {
      if (searchForm[key] !== '' && searchForm[key] !== null && searchForm[key] !== undefined) {
        cleanParams[key] = searchForm[key];
      }
    });
    
    const params = {
      ...cleanParams,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      // 添加时间戳避免缓存
      _t: Date.now()
    };
    
    console.log('请求参数:', params); // 调试日志
    
    api.stationInfoManage.getStationInfoPage(
      params,
      (response: any) => {
        console.log('响应数据:', response); // 调试日志
        // 根据测站数据要素管理组件的成功模式，修复数据解析逻辑
        if (response && response.data && response.data.code === 200) {
          const responseData = response.data.data;
          tableData.value.length = 0; // 清空现有数据
          
          // 处理数据，确保经纬度为正确的数字类型
          const processedList = (responseData.list || []).map(item => ({
            ...item,
            lon: item.lon !== null && item.lon !== undefined && item.lon !== '' 
              ? Number(item.lon) 
              : null,
            lat: item.lat !== null && item.lat !== undefined && item.lat !== '' 
              ? Number(item.lat) 
              : null
          }));
          
          tableData.value = processedList;
          pagination.total = responseData.total || 0;
          pagination.pageNum = responseData.pageNum || pagination.pageNum;
          pagination.pageSize = responseData.pageSize || pagination.pageSize;
        } else {
          ElMessage.error(response?.data?.message || response?.message || '查询失败');
        }
        loading.value = false;
      },
      (error: any) => {
        console.error('请求错误:', error); // 调试日志
        ElMessage.error('查询失败: ' + (error.message || error));
        loading.value = false;
      }
    );
  } catch (error) {
    console.error('异常错误:', error); // 调试日志
    ElMessage.error('查询失败');
    loading.value = false;
  }
};

const loadStationTypes = async () => {
  try {
    // 使用axios直接请求
    const response = await axios.get('/algorithmApi/api1/station-type1/list');
    if (response.data.code === 200) {
      stationTypes.value = response.data.data || [];
    } else {
      ElMessage.error(response.data.message || "获取测站类型选项失败");
    }
  } catch (error) {
    console.error("加载测站类型选项失败:", error);
    ElMessage.error("加载测站类型选项失败");
  }
};

const handleSearch = () => {
  pagination.pageNum = 1;
  loadData();
};

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = '';
  });
  pagination.pageNum = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = '新增测站';
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  isEdit.value = true;
  dialogTitle.value = '编辑测站';
  Object.assign(formData, row);
  dialogVisible.value = true;
};

const handleView = (row: any) => {
  Object.assign(detailData, row);
  detailVisible.value = true;
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除测站 "${row.stnm || row.stcd}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    api.stationInfoManage.deleteStationInfo(
      { id: row.id },
      (response: any) => {
        if (response.code === 200) {
          ElMessage.success('删除成功');
          loadData();
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      },
      (error: any) => {
        ElMessage.error('删除失败');
      }
    );
  });
};

const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const ids = selectedRows.value.map((row: any) => row.id);
    api.stationInfoManage.batchDeleteStationInfo(
      { ids },
      (response: any) => {
        if (response.code === 200) {
          ElMessage.success(`成功删除 ${response.data} 条记录`);
          loadData();
        } else {
          ElMessage.error(response.message || '批量删除失败');
        }
      },
      (error: any) => {
        ElMessage.error('批量删除失败');
      }
    );
  });
};

// 测站类型编码变化处理
const handleStationTypeCodeChange = (value: string) => {
  // 搜索表单中测站类型编码变化时的处理
  console.log('选择的测站类型编码:', value);
};

// 表单中测站类型变化处理
const handleFormStationTypeChange = (value: string) => {
  console.log('表单中选择的测站类型:', value);
};

const handleSave = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    saveLoading.value = true;
    
    const apiMethod = isEdit.value 
      ? api.stationInfoManage.updateStationInfo 
      : api.stationInfoManage.createStationInfo;
    
    apiMethod(
      formData,
      (response: any) => {
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
          dialogVisible.value = false;
          loadData();
        } else {
          ElMessage.error(response.message || '保存失败');
        }
        saveLoading.value = false;
      },
      (error: any) => {
        ElMessage.error('保存失败');
        saveLoading.value = false;
      }
    );
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

const handleBatchImport = () => {
  fileList.value = [];
  importVisible.value = true;
};

const handleFileChange = (file: any) => {
  fileList.value = [file];
};

const handleImportConfirm = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }
  
  importLoading.value = true;
  // 这里需要根据实际情况处理文件上传和解析
  // 示例代码，实际需要根据文件格式解析数据
  setTimeout(() => {
    ElMessage.success('导入成功');
    importVisible.value = false;
    importLoading.value = false;
    loadData();
  }, 2000);
};

const handleExport = () => {
  // 导出功能实现
  ElMessage.info('导出功能开发中...');
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageNum = page;
  loadData();
};

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'lon' || key === 'lat') {
      formData[key] = null;
    } else {
      formData[key] = '';
    }
  });
};

const getStationTypeName = (code: string) => {
  const type = stationTypes.value.find((t: any) => t.stationTypeCode === code);
  return type ? type.stationTypeName : code || '-';
};

const formatDate = (date: string) => {
  if (!date) return '-';
  return new Date(date).toLocaleString('zh-CN');
};
 // 视图高度
 const view = reactive({
    height: window.innerHeight,
  });
  window.onresize = function() {
    view.height = window.innerHeight;
  };
  
</script>

<style lang="scss" scoped>
.station-info-management {
  padding: 16px;
  
  .search-card,
  .operation-card,
  .table-card {
    margin-bottom: 16px;
  }
  
  .text-right {
    text-align: right;
  }
  
  .pagination-wrapper {
    margin-top: 16px;
    text-align: right;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  :deep(.el-upload-dragger) {
    width: 100%;
  }
}
</style>
